from celery import shared_task
from datetime import datetime
from .models import PhaseSummary
from .views import PhaseSummaryViewSet
from rest_framework.request import Request
from django.http import HttpRequest
from django.contrib.auth import get_user_model
from datetime import  timedelta
from django.utils import timezone
import logging
import json
from rest_framework.parsers import JSONParser
from .views import run_workflow, parse_workflow_response

logger = logging.getLogger('celery_tasks')

User = get_user_model()

# 定义产业列表
INDUSTRIES = [
    {"name": "人参", "keyword": "人参"},
    {"name": "新材料", "keyword": "碳纤维"},
    {"name": "人工智能", "keyword": "人工智能"}
]

# 定义报告风格和时间段
REPORT_STYLES = [
    {"id": 1, "name": "决策风格"},
    {"id": 2, "name": "创新风格"},
    {"id": 3, "name": "科研风格"}
]

REPORT_TYPES = [
    {"id": 1, "name": "月度"},
    {"id": 2, "name": "季度"},
    {"id": 3, "name": "年度"}
]

@shared_task
def generate_initial_reports():
    """系统初始化时生成报告"""
    try:
        print("\n=== 开始检查初始化报告 ===")
        
        # 使用定义在文件头部的产业列表
        for industry in INDUSTRIES:
            print(f"\n检查产业: {industry['name']}")
            
            # 检查是否存在最新报告
            latest_reports = PhaseSummary.objects.filter(
                industry=industry['name'],
                created_at__gte=timezone.now() - timedelta(days=30)  # 过滤一个月内的报告
            ).order_by('-created_at')

            if latest_reports.exists():
                print(f"已存在 {industry['name']} 一个月内的报告，跳过生成")
            else:
                print(f"未找到 {industry['name']} 一个月内的报告，开始生成...")
                
                # 构建生成列表，生成各种风格、各时间段的报告
                for style in REPORT_STYLES:
                    for report_type in REPORT_TYPES:
                        _generate_reports_for_industry(industry, style['id'], report_type['id'])
                
        # 打印所有报告列表
        all_reports = PhaseSummary.objects.all()
        print("\n=== 当前所有报告列表 ===")
        for report in all_reports:
            print(f"- {report.industry}: {report.title} ({report.created_at})")
                
    except Exception as e:
        print(f"\n=== 初始化报告生成失败 ===")
        print(f"错误信息: {str(e)}")
        logger.error(f"初始化报告生成失败: {str(e)}", exc_info=True)

@shared_task
def generate_monthly_reports():
    """每月1日生成月度报告"""
    try:
        # 使用定义在文件头部的产业列表
        for industry in INDUSTRIES:
            for style in REPORT_STYLES:
                _generate_reports_for_industry(industry, style['id'], report_type=1)  # 1表示月度
            
    except Exception as e:
        logger.error(f"月度报告生成失败: {str(e)}", exc_info=True)

@shared_task
def generate_quarterly_reports():
    """每季度生成季度报告"""
    try:
        # 使用定义在文件头部的产业列表
        for industry in INDUSTRIES:
            for style in REPORT_STYLES:
                _generate_reports_for_industry(industry, style['id'], report_type=2)  # 2表示季度
            
    except Exception as e:
        logger.error(f"季度报告生成失败: {str(e)}", exc_info=True)

@shared_task
def generate_yearly_reports():
    """每年生成年度报告"""
    try:
        # 使用定义在文件头部的产业列表
        for industry in INDUSTRIES:
            for style in REPORT_STYLES:
                _generate_reports_for_industry(industry, style['id'], report_type=3)  # 3表示年度
            
    except Exception as e:
        logger.error(f"年度报告生成失败: {str(e)}", exc_info=True)

def _generate_reports_for_industry(industry, report_style, report_type):
    """为指定产业生成阶段总结"""
    try:
        print(f"\n=== 开始为 {industry['name']} 生成阶段总结 ===")
        print(f"报告风格: {report_style}, 报告类型: {report_type}")
        
        # 获取系统管理员用户
        admin_user = User.objects.filter(is_superuser=True).first()
        if not admin_user:
            raise Exception("未找到系统管理员用户")
        print(f"使用管理员用户: {admin_user.username}")

        # 从预定义的列表中获取风格和类型的文本描述
        style_text = next((style['name'] for style in REPORT_STYLES if style['id'] == report_style), "科研风格")
        type_text = next((type['name'] for type in REPORT_TYPES if type['id'] == report_type), "年度")

        # 组合完整的context
        original_context = industry['keyword']
        full_context = f"{original_context}{type_text}{style_text}"

        # 直接调用 run_workflow 而不是通过视图
        response = run_workflow(
            workflow_name="阶段总结",
            inputs={
                "context": full_context,
                "user_id": str(admin_user.id),
            },
            user=str(admin_user.id)
        )
        
        content = parse_workflow_response(response)
        
        # 从内容中提取标题
        title = "阶段总结报告"
        lines = content.split('\n')
        for line in lines:
            if line.strip().startswith('###'):
                title = line.strip().replace('###', '').strip()
                break
        
        # 直接保存到数据库
        summary = PhaseSummary.objects.create(
            title=title,
            content=content,
            workflow_name=1,  # 阶段总结
            report_type=report_type,
            report_style=report_style,
            industry=industry['name'],
            user=admin_user
        )
        
        logger.info(f"成功为产业 {industry['name']} 生成阶段总结")
        print(f"=== {industry['name']} 阶段总结生成完成 ===\n")
        
        return summary
        
    except Exception as e:
        print(f"\n=== {industry['name']} 阶段总结生成失败 ===")
        print(f"错误信息: {str(e)}")
        logger.error(f"产业 {industry['name']} 阶段总结生成失败: {str(e)}", exc_info=True)
